﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO;

using Library.Bll;
using Library.Common;

namespace HanhuaMicroCredit.BLL.File
{
    public static class UploadBLL
    {
        /// <summary>
        /// 上传配置信息
        /// </summary>
        private static List<Dictionary<string, object>> _UploadConfigs;

        static UploadBLL()
        {
            SetUploadConfigs();
        }

        /// <summary>
        /// 加载上传配置信息
        /// </summary>
        public static void SetUploadConfigs()
        {
            _UploadConfigs = GetFileUploadSets(true);
        }

        /// <summary>
        /// 获取上传配置信息
        /// </summary>
        /// <param name="typeNo"></param>
        /// <returns></returns>
        public static Dictionary<string, object> GetUploadConfigs(string typeNo)
        {
            Dictionary<string, object> config = _UploadConfigs.FirstOrDefault(a => string.Equals(a["no"].ToString(), typeNo));
            if (config == null)
            {
                config = _UploadConfigs.FirstOrDefault(a => string.Equals(a["no"].ToString(), "default"));
            }

            return config;
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="typeNo">上传类型编号</param>
        /// <param name="files">文件</param>
        /// <param name="fileUrls">返回已上传文件路径</param>
        /// <returns></returns>
        public static string Upload(string typeNo, List<HttpPostedFileBase> files, out string fileUrls)
        {
            fileUrls = string.Empty;
            if ((files == null) || (files.Count == 0))
            {
                return "没有文件！";
            }

            string errorMsg = string.Empty;
            StringBuilder sbFileUrls = new StringBuilder();
            Dictionary<string, object> config = GetUploadConfigs(typeNo);

            int maxCount = Convert.ToInt32(config["maxcount"]);
            if ((maxCount > 0) && (files.Count > maxCount))
            {
                return string.Format("超过文件上传限制个数：{0}个", maxCount.ToString());
            }

            int maxSize = Convert.ToInt32(config["maxsize"]) * 1024;
            bool isImageServer = Convert.ToBoolean(config["isimageserver"]);

            List<Dictionary<string, object>> uploadLogs = new List<Dictionary<string, object>>();

            foreach (HttpPostedFileBase file in files)
            {
                if ((maxSize > 0) && (file.ContentLength > maxSize))
                {
                    errorMsg = string.Format("超过上传大小限制：{0}KB", config["maxsize"]);
                    break;
                }

                int dotIndex = file.FileName.LastIndexOf('.');
                string fileOriginalName, fileExtendName;
                if ((dotIndex > 0) && (dotIndex < file.FileName.Length))
                {
                    fileOriginalName = file.FileName.Substring(0, dotIndex);
                    fileExtendName = file.FileName.Substring(dotIndex);
                }
                else
                {
                    fileOriginalName = file.FileName;
                    fileExtendName = string.Empty;
                }

                string savePath = Path.Combine(config["savepath"].ToString(), DateTime.Today.ToString("yyyyMM"));
                string serverPath = HttpContext.Current.Server.MapPath(savePath);
                if (!Directory.Exists(serverPath))
                {
                    Directory.CreateDirectory(serverPath);
                }

                string no = Guid.NewGuid().ToString();
                string originalServerPath = string.Format("{0}/{1}{2}", serverPath, no, fileExtendName);
                string originalMapPath = string.Format("{0}/{1}{2}", savePath , no, fileExtendName);
                string returnFileName = config["returnfilename"].ToString().ToLower();

                try
                {
                    file.SaveAs(originalServerPath);
                }
                catch (Exception ex)
                {
                    errorMsg = string.Format("保存原始文件错误：{0}", ex.Message);
                    break;
                }

                Dictionary<string, object> fLog = new Dictionary<string, object>();
                fLog.Add("No", no);
                fLog.Add("TypeNo", typeNo);
                fLog.Add("OriginalName", file.FileName);
                fLog.Add("ContentLength", file.ContentLength.ToString());
                fLog.Add("ExtendName", fileExtendName);
                fLog.Add("ContentType", file.ContentType);
                fLog.Add("ServerPath", originalMapPath);
                string returnUrl = originalMapPath;

                try
                {
                    if (CommonHelper.IsImageFile(fileExtendName))
                    {
                        string thumbnailName = config["thumbnailname"].ToString();
                        if (!string.IsNullOrEmpty(thumbnailName))
                        {
                            //缩略图后缀不为空，需要保存缩略图
                            string thumbnailServerPath = string.Format("{0}/{1}{2}{3}", serverPath, no, thumbnailName, fileExtendName);
                            ImageHelper.MakeThumbnail(originalServerPath, thumbnailServerPath, Convert.ToInt32(config["thumbnailwidth"]), Convert.ToInt32(config["thumbnailheight"]), config["thumbnailmode"].ToString());
                            string thumbnailMapPath = string.Format("{0}/{1}{2}{3}", savePath, no, thumbnailName, fileExtendName);
                            fLog.Add("ThumbnailPath", thumbnailMapPath);
                            if (string.Equals(returnFileName, "thumbnail"))
                            {
                                //配置为返回缩略图路径
                                returnUrl = thumbnailMapPath;
                            }
                        }

                        string watermarkWords = config["watermarkwords"].ToString();
                        string watermarkWordsName = config["watermarkwordsname"].ToString();
                        if (!string.IsNullOrEmpty(watermarkWords) && !string.IsNullOrEmpty(watermarkWordsName))
                        {
                            //水印文字不为空，需要添加水印文字
                            string watermarkWordsServerPath = string.Format("{0}/{1}{2}{3}", serverPath, no, watermarkWordsName, fileExtendName);
                            ImageHelper.MakeWatermarkWord(originalServerPath, watermarkWordsServerPath, watermarkWords);
                            string watermarkWordsMapPath = string.Format("{0}/{1}{2}{3}", savePath, no, watermarkWordsName, fileExtendName);
                            fLog.Add("WatermarkWordsPath", watermarkWordsMapPath);
                            if (string.Equals(returnFileName, "watermarkwords"))
                            {
                                //配置为返回水印文字图片路径
                                returnUrl = watermarkWordsMapPath;
                            }
                        }

                        string watermarkImagePath = config["watermarkimagepath"].ToString();
                        string watermarkImageName = config["watermarkimagename"].ToString();
                        if (!string.IsNullOrEmpty(watermarkImagePath) && !string.IsNullOrEmpty(watermarkImageName))
                        {
                            //水印图片不为空，需要添加水印图片
                            string watermarkImageServerPath = string.Format("{0}/{1}{2}{3}", serverPath, no, watermarkImageName, fileExtendName);
                            ImageHelper.MakeWatermarkImage(originalServerPath, watermarkImageServerPath, HttpContext.Current.Server.MapPath(watermarkImagePath));
                            string watermarkImageMapPath = string.Format("{0}/{1}{2}{3}", savePath, no, watermarkImageName, fileExtendName);
                            fLog.Add("WatermarkImagePath", watermarkImageMapPath);
                            if (string.Equals(returnFileName, "watermarkimage"))
                            {
                                //配置为返回水印文字图片路径
                                returnUrl = watermarkImageMapPath;
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    InsLogBll.InsertLog("upload", "upload", e.ToString());
                }

                uploadLogs.Add(fLog);
                if (isImageServer && returnUrl.StartsWith("~/"))
                {
                    returnUrl = returnUrl.Remove(0, 2);
                }
                sbFileUrls.AppendFormat(";{0}", returnUrl);
            }

            if (errorMsg.Length > 0)
            {
                return errorMsg;
            }

            fileUrls = sbFileUrls.ToString().Substring(1);
            CommonBLL.Add("Log_UploadedFiles", uploadLogs);

            return string.Empty;
        }

        /// <summary>
        /// 获取上传文件设置
        /// </summary>
        /// <param name="isValid"></param>
        /// <returns></returns>
        public static List<Dictionary<string, object>> GetFileUploadSets(bool? isValid)
        {
            string selectFields = "No,Name,SavePath,MaxSize,MaxCount,FileTypes,IsImageServer,ThumbnailName,ThumbnailWidth,ThumbnailHeight,ThumbnailMode,"
                + "WatermarkWordsName,WatermarkWords,WatermarkImageName,WatermarkImagePath,ReturnFileName";
            string conditions = string.Empty;
            if (isValid.HasValue)
            {
                conditions = string.Format("IsValid={0}", isValid.Value ? "1" : "0");
            }

            return CommonBLL.GetList("Set_FileUpload", selectFields, string.Empty, conditions);
        }
    }
}
